package org.finesys.common.excel.aop;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.finesys.common.excel.annotaion.ResponseExcel;
import org.finesys.common.excel.handler.SheetWriteHandler;
import org.springframework.core.MethodParameter;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import cn.hutool.core.lang.Assert;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 导出excel 解析注解
 */
@Slf4j
@RequiredArgsConstructor
public class ResponseExcelReturnValueHandler implements HandlerMethodReturnValueHandler {
    private final List<SheetWriteHandler> sheetWriteHandlers;

    @Override
    public boolean supportsReturnType(@NonNull MethodParameter returnType) {
        return returnType.getMethodAnnotation(ResponseExcel.class) != null;
    }

    @Override
    public void handleReturnValue(@Nullable Object returnValue,@NonNull MethodParameter returnType,@NonNull ModelAndViewContainer mavContainer,@NonNull NativeWebRequest webRequest) throws Exception {
        HttpServletResponse response = webRequest.getNativeRequest(HttpServletResponse.class);
        Assert.state(response != null, "No HttpServletResponse!");
        ResponseExcel responseExcel = returnType.getMethodAnnotation(ResponseExcel.class);
        Assert.state(responseExcel != null, "No @ResponseExcel!");
        mavContainer.setRequestHandled(true);
        sheetWriteHandlers.stream().filter(handler -> handler.support(returnValue)).findFirst().ifPresent(handler -> {
            handler.export(returnValue, response, responseExcel);
        });
    }
}
